﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.Security;

public partial class Pages_UserManagement : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            InitUI();
        }
        BindGrid();
    }
    protected void btnCreateUser_Click(object sender, EventArgs e)
    {
        AddUsers();

    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {

    }

    private void InitUI()
    {
        IList<aspnet_Role> roleList = GetAllRoles();

        chkBLRoles.DataSource = roleList;
        chkBLRoles.DataValueField = "RoleId";
        chkBLRoles.DataTextField = "RoleName";
        chkBLRoles.DataBind();
    }

    private void BindGrid()
    {
        IList<MembershipUser> userList = Membership.GetAllUsers().OfType<MembershipUser>().ToList();

        var query = (from users in userList
                     select new
                     {
                         UserName = users.UserName,
                         ProviderUserKey = users.ProviderUserKey,
                         IsApproved = users.IsApproved
                     }).ToList();


        try
        {
            grdUsers.DataSource = query; // UserManager.GetAllUser();
        }
        catch
        {
            grdUsers.DataSource = null;
        }

        grdUsers.DataBind();
    }

    private List<string> GetSelectedRoles()
    {
        List<string> roleList = new List<string>();

        foreach (System.Web.UI.WebControls.ListItem role in chkBLRoles.Items)
        {
            if (role.Selected)
            {
                roleList.Add(role.Text);
            }
        }

        return roleList;
    }

    private void AddUsers()
    {
        string strPassword = "Asdf1234";

        if (!txtUserName.Enabled.Equals(false))
        {
            strPassword = txtPassword.Text;
        }

        List<string> roleList = GetSelectedRoles();

        if (roleList.Count < 1)
        {
            lblMessage.Text = "User role is not selected";
        }
        MembershipCreateStatus status;
        Membership.CreateUser(txtUserName.Text, strPassword, txtEmail.Text,null, null, chkActiveInactive.Checked, out status);

        if (status.Equals(MembershipCreateStatus.Success))
        {
            try
            {
                Roles.AddUserToRoles(txtUserName.Text, roleList.ToArray());
                lblMessage.Text = GetStatus(status);
            }
            catch
            {
                Membership.DeleteUser(txtUserName.Text);
                
            }
        }
        else 
        {
            lblMessage.Text = "User role Error: Account NOT created.";
        }
    }

    private string GetStatus(MembershipCreateStatus Status)
    {
        switch (Status)
        {
            case MembershipCreateStatus.Success:
                return ("The user account was successfully created!");
            case MembershipCreateStatus.DuplicateUserName:
                return ("That username already exists.");
            case MembershipCreateStatus.DuplicateEmail:
                return ("A user with that Email address already exists.");
            case MembershipCreateStatus.InvalidEmail:
                return ("PLease enter a VALID email address.");
            case MembershipCreateStatus.InvalidPassword:
                return ("The password entered is invalid. PLease enter a passoword with at least 7 cahacters and one non-alphanumeric.");
            default:
                return ("Unknown Error: Account NOT created.");
        }
    }

    //private bool UpdateUser()
    //{

    //    List<string> roleList = GetSelectedRoles();

    //    if (roleList.Count < 1)
    //    {
    //        lblMessage.Text = "User role is not selected";
    //        return false;
    //    }

    //    return new UserManager().UpdateUser(txtUserName.Text.Trim(), txtEmail.Text.Trim(), chkActiveInactive.Checked, roleList.ToArray());
    //}

    private IList<aspnet_Role> GetAllRoles()
    {
        IList<aspnet_Role> roleList = new List<aspnet_Role>();

        SqlConnection sqlConnection = new SqlConnection(DBConnection.ConnectionString);
        SqlCommand sqlCommand = new SqlCommand();
        string sql;
        sql = string.Format("select * from aspnet_Roles");
        sqlCommand.CommandText = sql;
        sqlCommand.Connection = sqlConnection;
        sqlCommand.CommandType = CommandType.Text;
        try
        {
            sqlConnection.Open();

            SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
            while (sqlDataReader.Read())
            {
                aspnet_Role role = new aspnet_Role();
                role.ApplicationId = new Guid(sqlDataReader["ApplicationId"].ToString());
                role.RoleId = new Guid(sqlDataReader["RoleId"].ToString());
                role.RoleName = sqlDataReader["RoleName"].ToString();
                role.LoweredRoleName = sqlDataReader["LoweredRoleName"].ToString();
                role.Description = sqlDataReader["Description"].ToString();
                roleList.Add(role);
            }


            sqlDataReader.Close();
        }
        catch (Exception ex)
        {
            return null;
        }
        finally
        {
            sqlConnection.Close();
        }
        return roleList;
    }
}
